package com.h.book.interceptor;


import com.h.book.constant.Constant;
import com.h.book.modle.Result;
import com.h.book.modle.UserInfo;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.nio.charset.StandardCharsets;

@Slf4j
@Component
// 自定义拦截器
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("preHandle.....目标方法执行前........");
        HttpSession session = request.getSession(false);
        if(!check(session)) {
            // 返回false，用户未登录
            // 设置文本
            response.setContentType("text/html;charset=utf-8");
            // 设置状态码
            response.setStatus(401); // 401是未登录
            // 设置返回结果
            String msg = "用户未登录";
            response.getOutputStream().write(msg.getBytes("UTF-8"));
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("postHandle.....");
    }

    private boolean check(HttpSession session) {
        if(session == null ||session.getAttribute(Constant.SESSION_USER_INFO) == null) {
            // 用户未登录
            log.warn("用户为登录");
            return false;
        }

        UserInfo userInfo = (UserInfo) session.getAttribute(Constant.SESSION_USER_INFO);
        if (userInfo == null || userInfo.getId() < 0) {
            log.warn("用户为登录");
            return false;
        }
        log.info("用户已登录");
        return true;
    }

//    @Override
//    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        // 图像渲染方面的，不需要进行处理
//        log.info("afterCompletion.....");
//    }
}
